package com.zxd.interview.eightthread.deathlock;

/**
 * 两个线程必定发生死锁的代码例子
 * @author Xander
 * @version v1.0.0
 * @Package : com.zxd.interview.eightthread.deathlock
 * @Description : 两个线程必定发生死锁的代码例子
 * @Create on : 2023/3/28 12:24
 **/
public class MultiThreadError implements Runnable{

    private static final Object lock1 = new Object();
    private static final Object lock2 = new Object();

    int flags = 0;

    public static void main(String[] args) throws InterruptedException {
        MultiThreadError multiThreadError1 = new MultiThreadError();
        MultiThreadError multiThreadError2 = new MultiThreadError();
        multiThreadError2.flags = 1;
        Thread thread1 = new Thread(multiThreadError1);
        Thread thread2 = new Thread(multiThreadError2);
        thread1.setName("线程1");
        thread2.setName("线程2");
        thread1.start();
        thread2.start();

    }

    @Override
    public void run() {

        if(flags == 0){
            synchronized (lock1){
                System.out.println(Thread.currentThread().getName() + "获取到锁 lock1");
                synchronized (lock2){
                    System.out.println(Thread.currentThread().getName() + "获取到锁 lock2");
                }
                System.out.println(Thread.currentThread().getName() + "释放锁lock2");
            }

            System.out.println(Thread.currentThread().getName() + "释放锁lock1");
        }

        if(flags == 1){
            synchronized (lock2){
                System.out.println(Thread.currentThread().getName() + "获取到锁 lock2");
                synchronized (lock1){
                    System.out.println(Thread.currentThread().getName() + "获取到锁 lock1");
                }
                System.out.println(Thread.currentThread().getName() + "释放锁lock1");
            }

            System.out.println(Thread.currentThread().getName() + "释放锁lock2");
        }


    }/**
     必然死锁，结果如下：
     线程1获取到锁 lock1
     线程2获取到锁 lock2
     */
}
